const { order, user } = require('../model/db');
const nodemailer = require('nodemailer');
const moment = require('moment');

const transporter = nodemailer.createTransport({
  host: "smtp.qq.com",     // SMTP服务器地址
  port: 465,     // SMTP端口
  secure: true,   // 使用SSL/TLS
  auth: {
    user: "wq3stone@qq.com",  // 邮箱账号
    pass: "xxxxxx"    // 邮箱密码或应用专用密码
  }
});

// 发送邮件
async function sendEmail(to, subject, html) {
  const mailOptions = {
    from: 'wq3stone<wq3stone@qq.com>',  // 发件人
    to: to,     // 收件人
    subject: subject,     // 主题
    html: html   // HTML内容
  };

  try {
    const info = await transporter.sendMail(mailOptions);
    console.log("邮件发送成功:", info.accepted);
    return info;
  } catch (error) {
    console.error("邮件发送失败:", error);
    throw new Error("邮件发送失败");
  }
}

async function matchCarpoolOrder(orderContent) {
  try {
    const { openid, startAddress, endAddress } = orderContent;
    const { startTime, endTime, email } = orderContent.info;

    // 查询符合条件的订单
    const orders = await order.aggregate([
      {
        $match: {
          $and: [
            { openid: { $ne: openid } },
            { orderType: '拼车匹配' },
            { status: '正在拼' },
            { startAddress: startAddress },
            { endAddress: endAddress }
          ],
          $expr: {
            $and: [
              { $lt: ["$info.startTime", endTime] },
              { $gt: ["$info.endTime", startTime] },
            ]
          }
        }
      },
      {
        $project: {
          _id: 1,
          openid: 1,
          "info.email": 1,
          "info.startTime": 1,
          "info.endTime": 1,
          "info.overlappingStartTime": {
            $max: [startTime, '$info.startTime']
          },
          "info.overlappingEndTime": {
            $min: [endTime, '$info.endTime']
          }
        }
      },
      {
        $sort: {
          publicTime: 1
        }
      }
    ]);

    if (orders.length === 0) {
      await sendEmail(email,"拼车订单提醒",`您的<font color='red'><b>${startAddress}</b></font>到<font color='red'><b>${endAddress}</b></font>的订单(<font color='blue'><b>${startTime}</font></b>--><font color='blue'><b>${endTime}</b></font>)正在匹配中，成功后会邮件提醒您！`)
      console.log("没有找到符合条件的订单");
      return;
    } else {
      const matchedOrder = orders[0];
      console.log(matchedOrder)
      // 更新匹配到的订单
      await order.updateOne(
        { _id: matchedOrder._id },
        {
          $set: {
            "acceptMan": orderContent.openid,
            'info.acceptId': orderContent._id,
            "status": '已拼成',
            "info.overlappingStartTime": matchedOrder.info.overlappingStartTime,
            "info.overlappingEndTime": matchedOrder.info.overlappingEndTime
          }
        }
      );
      await sendEmail(matchedOrder.info.email,"拼车订单提醒",`您的<font color='red'><b>${startAddress}</b></font>到<font color='red'><b>${endAddress}</b></font>的订单(<font color='blue'><b>${matchedOrder.info.startTime}</b></font>--><font color='blue'><b>${matchedOrder.info.endTime}</b></font>)已经匹配成功，请登录小程序查看！`)
      // 更新当前订单
      await order.updateOne(
        { _id: orderContent._id },
        {
          $set: {
            "acceptMan": matchedOrder.openid,
            'info.acceptId': matchedOrder._id,
            "status": '已拼成',
            "info.overlappingStartTime": matchedOrder.info.overlappingStartTime,
            "info.overlappingEndTime": matchedOrder.info.overlappingEndTime
          }
        }
      );
      await sendEmail(email,"拼车订单提醒",`您的<font color='red'><b>${startAddress}</b></font>到<font color='red'><b>${endAddress}</b></font>的订单(<font color='blue'><b>${startTime}</b></font>--><font color='blue'><b>${endTime}</b></font>)已经匹配成功，请登录小程序查看！`)
      console.log("订单匹配成功");
    }

  } catch (error) {
    console.error("订单匹配失败:", error);
    throw new Error("订单匹配失败");
  }
}

module.exports = {
  sendEmail,
  matchCarpoolOrder,
};